package com.scs.application.modules.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.base.entity.Dept;
import com.scs.application.modules.base.mapper.DeptMapper;
import com.scs.application.modules.base.service.DeptService;
import com.scs.application.modules.base.service.UserWarehouseService;
import com.scs.application.modules.base.vo.UserWarehouseVO;
import com.scs.application.modules.report.handler.BeforeReport;
import com.scs.application.modules.sys.entity.Office;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.sys.service.OfficeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 院方科室 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/base/dept")
public class DeptController extends CrudController<DeptService, Dept> {


    @Autowired
    private UserWarehouseService userWarehouseService;

    @Autowired
    private OfficeService officeService;

    @Resource
    @Lazy
    private DeptMapper deptMapper;
    /**
     * 添加/更新数据
     */
    @RequestMapping(value = "/syncOffice", method = RequestMethod.POST)
    public RestResult syncOffice() {
        Integer updateCount = service.syncOffice();
        return RestResult.ok("数据同步成功", updateCount);
    }

    /**
     * 列出所有业务科室
     *
     * @return
     */
    @GetMapping("/listBusDept")
    public RestResult listBusDept() {
        List<Dept> list = service.list(new QueryWrapper<Dept>().eq("flag_bus", true));
        return RestResult.ok("查询成功", list);
    }

    /**
     * 列出所有业务科室
     *
     * @return
     */
    @GetMapping("/list")
    @Override
    public RestResult list() {
        List<Dept> list = service.list(new QueryWrapper<Dept>().eq("flag_bus", true));
        return RestResult.ok("查询成功", list);
    }

    /**
     *  获取用户关联科室
     * @return
     */
    @GetMapping("/listByUserId")
    public RestResult listByUserId(){
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> params = queryContext.getParams();
        String user_id = (String) params.get("user_id");
        String dept_id = (String) params.get("dept_id");
        if (StringUtils.isBlank(user_id) && UserUtils.isAdmin()) {
            return RestResult.ok("查询成功", service.list());
        }
        if (StringUtils.isBlank(user_id)) user_id = UserUtils.currentUser().getId();
        if (StringUtils.isBlank(dept_id)) dept_id = UserUtils.currentUser().getDeptId();
        List<Dept> list = service.listByUserId(user_id,dept_id);
        return RestResult.ok("查询成功", list);
    }


    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody Dept entity) {
        //查看科室是否被占用
        if(StringUtils.isNotBlank(entity.getWarehouseId())){
            Dept dept=service.getOne(Wrappers.<Dept>query().eq("warehouse_id",entity.getWarehouseId()). ne("id",entity.getId()));
            if(dept != null) {
                throw new BusinessException("您所选择的仓库【%s】已被【%s】使用，请更换其他的", dept.getWarehouseName(), dept.getName());
            }
        }
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        return RestResult.ok("数据保存成功",  entity);
    }

    /**
     * 选择 获取数据列表
     */
    @GetMapping("/pageForSelect")
    public PageResult pageForSelect(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> userParam =null;
        //固定参数
        if(reqData.containsKey("userParam")){
            JSONObject ob = JSON.parseObject(reqData.get("userParam")+"");
            userParam= Maps.newHashMap(ob);
        }
        //登录用户可用工位
        List<UserWarehouseVO> userWarehouseList = userWarehouseService.getUserWarehouse();
        List<String> ids = new ArrayList<>();
        userWarehouseList.forEach(userWarehouse -> {
            if (StringUtils.isNotBlank(userWarehouse.getDeptId())) {
                ids.add(userWarehouse.getDeptId());
            }
        });
        if(userWarehouseList == null || userWarehouseList.size() <1)   return null;
        //非全院权限
        if(!BeforeReport.getFlagAllData()){
            queryContext.getWrapper().in("id", ids);
        }

        IPage pageResult = service.pageForSelect(queryContext,userParam);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    /**
     * 选择 获取数据列表
     */
    @GetMapping("/listForSelect")
    public RestResult listForSelect(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> userParam =null;
        //固定参数
        if(reqData.containsKey("userParam")){
            JSONObject ob = JSON.parseObject(reqData.get("userParam")+"");
            userParam= Maps.newHashMap(ob);
        }
        //登录用户可用工位
        List<UserWarehouseVO> userWarehouseList = userWarehouseService.getUserWarehouse();
        List<String> ids = new ArrayList<>();
        userWarehouseList.forEach(userWarehouse -> {
            if (StringUtils.isNotBlank(userWarehouse.getDeptId())) {
                ids.add(userWarehouse.getDeptId());
            }
        });
        if(userWarehouseList == null || userWarehouseList.size() <1)   return null;
        //非全院权限
        if(!BeforeReport.getFlagAllData()){
            queryContext.getWrapper().in("id", ids);
        }

        return RestResult.ok("查询成功", deptMapper.listForSelect(queryContext.getWrapper(), queryContext.getParams(),userParam));
    }


    /**
     * 选择 科室病人消耗明细报表-执行科室
     */
    @GetMapping("/pageForDeptOprtUseExec")
    public PageResult pageForDeptOprtUseExec(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> userParam =null;
        //固定参数
        if(reqData.containsKey("userParam")){
            JSONObject ob = JSON.parseObject(reqData.get("userParam")+"");
            userParam= Maps.newHashMap(ob);
        }



            //查询存在病人消耗单里面的 执行科室
            queryContext.getWrapper().inSql("id","select distinct exec_dept_id from dept_oprt_use ");


        IPage pageResult = service.pageForSelect(queryContext,userParam);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }



    /**
     * 列出所有业务科室
     *
     * @return
     */
    @GetMapping("/pageBusDept")
    public PageResult pageBusDept() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        queryContext.getWrapper().eq("flag_bus",1);
        IPage pageResult = service.page(queryContext);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }


    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    @Override
    public RestResult find(@RequestParam("id") Serializable id) {
        Dept entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }

        if (StringUtils.isNotBlank(entity.getOfficeId())) {
            Office entityFind = officeService.getById(entity.getOfficeId());
            if (entityFind != null)  {
                entity.setOfficeName(entityFind.getName());
            }
        }

        return RestResult.ok("获取数据成功", entity);
    }
}
